/**
 * 产品品类
 */
import { message } from 'antd';
import { query, create, remove, update } from '../services/productType';
import createModel from './base';
import { config } from '../configs';
import error from '../configs/error';

const { prefix } = config;

export default createModel({
	namespace: 'productType',

	state: {

	},

	subscriptions: {
		setup({ dispatch, history }) {
			history.listen(location => {
				if (location.pathname === '/productType') { // 每次刷新一下，获取最新
					dispatch({
						type: 'query'
					});
				}
			});
		},
	},

	effects: {
		*update({ payload }, { select, call, put }) {
			const old = yield select(state => state.productType.list.find(t => t.id === payload.id));
			const currentItem = yield select(state => state.productType.currentItem);
			const newOne = { ...old, ...payload, utime: new Date() * 1 };
			yield put({ type: 'updateOne', payload: newOne });
			const res = yield call(update, payload);
			if (res.code === error.success.code) {
				yield put({
					type: 'productList/query',
				});
				message.success('更新成功');
				return;
			} else {
				yield put({ type: 'updateOne', payload: { ...newOne } });
				throw res;
			}
		}
	},
	reducers: {
		updateOne(state, { payload }) {
			const list = state.list.map(t => t.id === payload.id ? { ...t, ...payload } : t);
			return { ...state, list, currentItem: payload };
		},
	},
}, query, create, remove, update);
